package com.cdfy.controller;

import com.auth0.jwt.JWT;
import com.cdfy.bean.TokenBean;
import com.cdfy.bean.UserBean;
import com.cdfy.jwt.JwtUtils;
import com.cdfy.jwt.PassToken;
import com.cdfy.jwt.UseToken;
import com.cdfy.service.UserService;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;

@RestController
public class UserApi {

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PassToken
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        TokenBean tokenBean = new TokenBean();
        UserBean base = new UserBean();
        base.setId("1");
        base.setUsername("hutao");
        base.setPassword("123456");
        if (username.equals(base.getUsername()) && password.equals(base.getPassword())) {
            TokenBean token = JwtUtils.getToken(base);
            tokenBean.setErrCode(0);
            tokenBean.setMessage("success");
            tokenBean.setToken(token.getToken());
            tokenBean.setExpDate(token.getExpDate());
        }
        else {
            tokenBean.setErrCode(1);
            tokenBean.setMessage("用户名或密码错误");
        }
        return new Gson().toJson(tokenBean);
    }

    @UseToken
    @RequestMapping(value = "/getUserInfo")
    public String getUserInfo(@RequestHeader("token") String token) {
        String userId = JWT.decode(token).getAudience().get(0);
        UserService userService = new UserService();
        UserBean userBean = userService.getUserInfo(userId);
        return new Gson().toJson(userBean);
    }

    @PassToken
    @RequestMapping(value = "/helloworld")
    public String helloWorld() {
        return "Hello World";
    }
}
